package com.aizhaiyu.blue_record

import android.content.Context
import android.os.Handler
import android.os.Looper
import io.flutter.embedding.engine.plugins.FlutterPlugin
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugin.common.MethodChannel.MethodCallHandler
import io.flutter.plugin.common.MethodChannel.Result
import io.flutter.plugin.common.EventChannel

class BlePeripheralPlugin: FlutterPlugin, MethodCallHandler {
    private lateinit var methodChannel: MethodChannel
    private lateinit var eventChannel: EventChannel
    private lateinit var context: Context
    private lateinit var bleService: BlePeripheralService
    private var eventSink: EventChannel.EventSink? = null
    private val mainHandler = Handler(Looper.getMainLooper())

    override fun onAttachedToEngine(binding: FlutterPlugin.FlutterPluginBinding) {
        methodChannel = MethodChannel(binding.binaryMessenger, "blue_record/ble_peripheral")
        eventChannel = EventChannel(binding.binaryMessenger, "blue_record/ble_peripheral_events")
        context = binding.applicationContext
        
        bleService = BlePeripheralService(context) { command ->
            // 确保在主线程上发送事件
            mainHandler.post {
                eventSink?.success(command)
            }
        }
        
        methodChannel.setMethodCallHandler(this)
        eventChannel.setStreamHandler(object : EventChannel.StreamHandler {
            override fun onListen(arguments: Any?, events: EventChannel.EventSink?) {
                eventSink = events
            }

            override fun onCancel(arguments: Any?) {
                eventSink = null
            }
        })
    }

    override fun onDetachedFromEngine(binding: FlutterPlugin.FlutterPluginBinding) {
        methodChannel.setMethodCallHandler(null)
        eventChannel.setStreamHandler(null)
        mainHandler.removeCallbacksAndMessages(null)
    }

    override fun onMethodCall(call: MethodCall, result: Result) {
        when (call.method) {
            "startAdvertising" -> {
                try {
                    bleService.startAdvertising()
                    result.success(null)
                } catch (e: Exception) {
                    result.error("START_ADVERTISING_ERROR", e.message, null)
                }
            }
            "stopAdvertising" -> {
                try {
                    bleService.stopAdvertising()
                    result.success(null)
                } catch (e: Exception) {
                    result.error("STOP_ADVERTISING_ERROR", e.message, null)
                }
            }
            "sendNotification" -> {
                try {
                    val message = call.argument<String>("message")
                    if (message != null) {
                        bleService.sendNotification(message.toByteArray())
                        result.success(null)
                    } else {
                        result.error("INVALID_ARGUMENT", "Message cannot be null", null)
                    }
                } catch (e: Exception) {
                    result.error("SEND_NOTIFICATION_ERROR", e.message, null)
                }
            }
            else -> result.notImplemented()
        }
    }
} 